<template>
  <el-dialog
    :destroy-on-close="true"
    :visible="isShow"
    @close="closeModal"
  >
    <fm-generate-form
      ref="formRef"
      v-loading="loading"
      :data="formConfig"
    />

    <span slot="footer">
      <el-form label-suffix=":" :inline="true">
        <el-form-item label="接收用户">
          <el-select v-model="user">
            <el-option value="test1" label="test1" />
            <el-option value="test2" label="test2" />
            <el-option value="test3" label="test3" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-button @click="closeModal">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save">保存并启动</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { GetFormConfig, StartFlow, SaveFormData } from '@/api/formManagement';

export default {
  name: 'StartFlowModal',
  props: {
    isShow: {
      type: Boolean,
      required: true,
      default: false
    },
    flowID: {
      type: String,
      required: true,
      default: ''
    },
    flowName: {
      type: String,
      required: true,
      default: ''
    },
    formID: {
      type: Number,
      required: true,
      default: null
    }
  },
  data() {
    return {
      formConfig: { list: [], config: {}},
      loading: false,
      user: 'test2'
    };
  },
  mounted() {
    this.getFormConfig();
  },
  methods: {
    closeModal() {
      this.$emit('update:isShow', false);
    },
    getFormConfig() {
      GetFormConfig(this.formID).then(res => {
        const { config } = res.data;
        this.formConfig = JSON.parse(config);
      }, err => {
        this.$message.error(err.msg);
      });
    },
    save() {
      this.loading = true;

      this.$refs['formRef'].getData().then(data => {
        const params = {
          userNo: 'test1',
          flowNo: this.flowID,
          sysNo: '1001',
          toEmps: this.user
        };
        return new Promise((resolve, reject) => {
          StartFlow(params).then(res => {
            resolve({ ...res.data, data });
          }, err => {
            reject(err);
          });
        });
      }, err => {
        this.loading = false;
        this.$message.warning(err);
      }).then(res => {
        const { data, workId } = res;
        const params = { workId: workId, formId: this.formID, data };
        return SaveFormData(params);
      }, err => {
        this.loading = false;
        this.$message.error(err.message);
      }).then(res => {
        this.loading = false;
        this.$message.success(res.msg);
        this.closeModal();
      }, err => {
        this.loading = false;
        this.$message.error(err.message);
      });
    }
  }
};
</script>

<style scoped>

</style>
